// pages/article/article.js
import { request } from "../../request/request";
import moment from "../../utils/moment";
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';

//获取应用实例
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //加载中
    loading: false,
    userId: 0,
    position: false,
    //父评论Id
    parentCommentId: 0,
    //评论内容
    content: '',
    articleId: 0,
		isLoading: true,					// 判断是否尚在加载中
    result: {},
    show: false,
    placeholder: '请输入评论：',
    //文章信息
    article: {},
    //评论信息
    listCommentVo: [],
    //到底了
    isMore: false,
    //分页、
    pageNo: 1,
    pageSize: 5,
    total: 0,
    hits: 0,
    commentAmount: 0,
    color: [
      '#6739b6',
      '#9c26b0',
      '#0081ff',
      '#e03997',
      '#8799a3',
      '#39b54a',
      '#1cbbb4'
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let articleId = options.articleId;
    console.log(articleId);
    this.setData({
      articleId
    })
    const userInfo = wx.getStorageSync('userInfo');
    if(userInfo !== null && userInfo !== '') {
      this.setData({
        userId: userInfo.userId,
        position: userInfo.position
      })
    }
    this.getarticle(articleId);
    this.listCommentVo(articleId);
  },
  //获取数据
  async getarticle(articleId) {

    this.setData({
      loading: true
    })

    const res = await request({
      url: '/article/getArticleById',
      data: {
        articleId
      }
    })
    console.log(res);
    if(res.code === 2000) {
      let article = res.data.article;
      article.gmtCreate = moment(article.gmtCreate).format("MMMM Do YYYY, h:mm:ss a");
      article.gmtModified = moment(article.gmtModified).format("MMMM Do YYYY, h:mm:ss a");
      let hits = res.data.hits;
      let commentAmount = res.data.commentAmount;
      let result = app.towxml(article.contentMd,'markdown',{
        theme:'light',					// 主题，默认`light`
        events:{					// 为元素绑定的事件方法
          tap:(e)=>{
            console.log('tap',e);
          }
        }
      });
      // 更新解析数据
      this.setData({
        result:result,
        isLoading: false,
        article,
        hits,
        commentAmount
      });
      this.setData({
        loading: false
      })
    }
    
  },
  //获取评论信息
  async listCommentVo(articleId) {
    const pageNo = this.data.pageNo;
    const pageSize = this.data.pageSize;
    this.setData({
      loading: true
    })
    const res = await request({
      url: '/comment/listCommentVo',
      data: {
        pageNo,
        pageSize,
        articleId
      }
    })
    if(res.code === 2000) {
      const listCommentVo = res.data.commentVoList;
      const total = res.data.total;
      listCommentVo.forEach(element => {
        element.gmtCreate = moment(element.gmtCreate).format("MMMM Do YYYY, h:mm:ss a");
        if(element.childrenComments.lenght !== 0) {
          element.childrenComments.forEach(children => {
            children.gmtCreate = moment(children.gmtCreate).format("MMMM Do YYYY, h:mm:ss a");
          })
        }
      });
      this.setData({
        listCommentVo,
        total
      })
      this.setData({
        loading: false
      })
    }
  },
  onOpen() {
    if(this.data.userId === 0) {
      Notify({ type: 'danger', message: '请先登录！' });
      return;
    }
    this.setData({ show: true });
  },
  onInput(event) {
    this.setData({
      content: event.detail
    })
  },
  onClose() {
    this.setData({
      content: '',
      placeholder: '请输入评论：',
      parentCommentId: 0
    })
    this.setData({ show: false });
  },
  async onConfirm() {
    let articleId = this.data.articleId;
    let content = this.data.content;
    let parentCommentId = this.data.parentCommentId;
    let userId = this.data.userId;
    if(content === '') {
      Notify({ type: 'danger', message: '评论不能为空！' });
      return;
    }
    const res = await request({
      url: '/comment/insertComment',
      method: 'post',
      data: {
        articleId,
        parentCommentId,
        content,
        userId
      }
    })
    if(res.code === 2000) {
      Notify({ type: 'success', message: '发表评论成功！' });
      this.listCommentVo(this.data.articleId);
      this.onClose();
    }
  },
  //删除评论
  async delete(e) {
    let commentId = e.target.dataset.id;
    console.log(commentId);
    const res = await request({
      url: '/comment/deleteComment',
      method: 'delete',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        commentId
      }
    })
    if(res.code === 2000) {
      Notify({ type: 'success', message: '删除评论成功！' });
      this.listCommentVo(this.data.articleId);
    }
    
  },
  //回复评论
  reply(e) {
    let index = e.target.dataset.index;
    console.log(index);
    let messageId = this.data.listCommentVo[index].id;
    let nickname = this.data.listCommentVo[index].nickname;
    console.log(messageId);
    console.log(nickname);
    if(this.data.userId === 0) {
      Notify({ type: 'danger', message: '请先登录！' });
      return;
    }
    this.setData({
      placeholder: '回复：'+nickname,
      parentCommentId: messageId,
      show: true
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let pageNo = this.data.pageNo;
    if(pageNo * this.data.pageSize >= this.data.total) {
      console.log("没有数据了")
      this.setData({
        isMore: true
      })
      return;
    }
    this.setData({
      pageNo: pageNo + 1
    })
    console.log("触底了");
    this.listCommentVo(this.data.articleId);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})